import axios from "axios";
import { ElMessage } from 'element-plus'
import { Decrypt } from '@/utils/secret.js'
import router from '../router';


const instance = axios.create({
    //网络请求公共参数
    timeout: 300000,
    baseURL: import.meta.env.VITE_BASE_URL
})
//拦截器
//发送数据之前
instance.interceptors.request.use(
    //成功直接返回
    config => {
        const userStr = window.localStorage.getItem("access-admin")
        if (userStr) {
            const token = JSON.parse(userStr).token
            config.headers.token = Decrypt(token)
            config.headers.accessAuthor = 'allow'
        }
        return config;
    },
    //失败返回错误信息
    error => {
        return Promise.reject(error)
    }
)
//获取数据之前
instance.interceptors.response.use(
    response => {
        if (response.status === 200) {
            //权限失效
            if (response.data.code === 401) {
                router.push('/login')
            }
            //离线 
            else if (response.data.code === 402) {
                localStorage.removeItem("access-admin")
                router.push('/login')
            }
            return Promise.resolve(response)
        }
        return Promise.reject(response)
    },
    error => {
        ElMessage.error('服务响应失败,请检查网络或联系系统管理员！')
        return Promise.reject(error)
    }
)
export default instance